/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.jm.financeiro.filter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 *
 * @author joao
 */
public class EmailValidator implements Validator {

    @Override
    public void validate(FacesContext facesContext, UIComponent uIComponent, Object object) throws ValidatorException {

        String enteredEmail = (String) object;
        // ".+@.+\\.[a-z]+"

        if (!enteredEmail.isEmpty()) {
            Pattern p = Pattern.compile("^[\\w\\-]+(\\.[\\w\\-]+)*@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$");
            Matcher m = p.matcher(enteredEmail);

            boolean matchFound = m.matches();

            if (!matchFound) {
                FacesMessage message = new FacesMessage();
                message.setDetail("E-mail incorreto!");
                message.setSummary("E-mail incorreto!");
                message.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(message);
            }
        }
    }
}
